
var child_process = require('child_process')
var fs = require("fs")
var qs = require('querystring');
var url = require("url")
var path = require('path')

require('./functions.js')

var segX = '_'

this.getRunGame = function(req, res) 
{ 
    res.write(getHtml_games('run'))
    res.end()
}

this.postRunGame = function(req, res) 
{
    var queryUrl = url.parse(req.url).query 
    var query = qs.parse(queryUrl)
    var gameName = query.gameName
    if(!gameName)
    {
      var result = ''
      var cmd = 'rm -r runtime/publicres;' + 
      'rm -r runtime/project.json;' + 
      //'rm -r runtime/src;' + 
      'ln -s ' + process.cwd() + '/public/res runtime/publicres;' +  //ln -s 第一个路径必须是绝对路径
      'ln -s ' + process.cwd() + '/public/publishCocos/project.json runtime/project.json;'
      //'ln -s ' + process.cwd() + '/public/src runtime/src;'

      child_process.execSync(cmd)
      res.redirect('/')
    }
    else
    {
      runGame(gameName)
      res.end()
    }
}

this.getPublishGame = function(req, res) 
{ 
    res.write(getHtml_games('publish'))
    res.end()
}

this.postPublishGame = function(req, res) 
{
    var queryUrl = url.parse(req.url).query 
    var query = qs.parse(queryUrl)
    var gameName = query.gameName
    if(!gameName)
    {
      var cmd = 'rm -rf publish/*;' +
      'cp public/publishGameFrame/game.min.js publish/public.min.js;' + 
      'cp -r public/publishGameFrame/res publish/publicres;' + 
      'cp public/publishGameFrame/project.json publish/project.json;'
      child_process.execSync(cmd)
      res.redirect('/')
    }
    else
    {
      publishGame(gameName)
      res.end()
    }
}

//输入c++代码 返回js代码
this.getC2js = function(res) 
{
    var body = '<html>'+
    '<head>'+
    '<meta http-equiv="Content-Type" '+
    'content="text/html; charset=UTF-8" />'+
    '<script src="/javascripts/headScripts.js"></script>'+ 
    '<link rel="stylesheet" href="/stylesheets/style.css" />'+
    '</head>'+
    '<body>'+
    '<p><a href="/">首页</a></p>'+
    '<textarea rows="8" cols="150" id= "c">c</textarea><br><br><br>'+
    '<textarea rows="8" cols="150" id= "js">js</textarea>'+
    '<p><button onclick="c2js()">转换</button></p>'+
    '</body>'+
    '</html>'

    res.writeHead(200, {"Content-Type": "text/html"})
    res.write(body)
    res.end()
}

this.getPublishCocos = function(res) 
{ 
    var cmd = 'cp public/projectCocos.json public/project.json;' +
    'cd public;/usr/bin/env cocos compile -p web -m release -o publishCocos' 

    child_process.exec(cmd, function(error)
               {
                  if(error)
                  {
                    res.render('index', { title: 'index' , tips: "error:" + error})
                  }
                  else
                    res.render('index', { title: 'index' , tips: "success"})
               })

}

this.getPublishGameFrame = function(res) 
{ 
    var cmd = 'cp public/projectGameFrame.json public/project.json;' +
    'cd public;/usr/bin/env cocos compile -p web -m release -o publishGameFrame' 

    child_process.exec(cmd, function(error)
               {
                  if(error)
                  {
                    res.render('index', { title: 'index' , tips: "error:" + error})
                  }
                  else
                    res.render('index', { title: 'index' , tips: "success"})
               })

}

////////////////////////////////////////////////////////////////////////////////////////////////////

//不加新js文件可以直接刷新调试 加了新的js需要重新运行（相比cocos的调试快很多了）
function runGame(gameName)
{   
    try
    { 
      var idx = gameName.split(segX)[0]
      var cmd =  'rm -r runtime/' + idx + 'res;' + 
      'ln -s ' + process.cwd() + '/games/' + gameName + '/res runtime/' + idx + 'res;' + 
      'cp games/' + gameName + '/index.html runtime/' + idx + '.html;' 

      child_process.execSync(cmd)

      var appendHtml = ''
      function handleFile(filePath) 
      {    
          if(path.extname(filePath) == '.js')
          {
              appendHtml  = appendHtml + '<script src="/poker/' + filePath + '"></script>' + '\n'
          }
      }  
      //包含cocos引擎
      handleFile('public/publishCocos/game.min.js')
      //包含public/src 下所有js
      walkFiles('public/src', 0, handleFile) 
      //包含niuniu/baseData.js
      handleFile('games/' + gameName + '/baseData.js')
      //包含niuniu/src
      walkFiles('games/' + gameName + '/src', 0, handleFile) 
      //包含niuniu/main.js
      handleFile('games/' + gameName + '/main.js')

      appendHtml = appendHtml + '</body>' + '\n' +'</html>'

      fs.appendFileSync('runtime/' + idx + '.html',appendHtml)
      return gameName.split(segX)[1] + ':success '
    }
    catch(e)
    {
      return gameName.split(segX)[1] + ':error ' + e
    }

}

function publishGame(gameName)
{   
    try
    { 
      var idx = gameName.split(segX)[0]
      minifyJs(['games/'+gameName+'/baseData.js', 
        'games/'+gameName+'/src', 
        'games/'+gameName+'/main.js' ], 'publish/' + idx + '.min.js')

      var cmd = 'cp -r games/' + gameName + '/res publish/' + idx + 'res;'+
      'cp games/' + gameName + '/index.html publish/' + idx + '.html;' 
    //'/usr/bin/env cocos compile -p web -m release' + 
      child_process.execSync(cmd)

      var appendHtml = '<script src="public.min.js"></script>' + '\n' +
      '<script cocos src="1.min.js"></script>' + '\n' +
      '</body>' + '\n' +
      '</html>'

      fs.appendFileSync('publish/' + idx + '.html',appendHtml)
      return gameName.split(segX)[1] + ':success '
    }
    catch(e)
    {
      return gameName.split(segX)[1] + ':error ' + e
    }

}

function getHtml_games(actionName)
{
    var html =
    '<head>'+
    '<meta http-equiv="Content-Type" '+
    'content="text/html; charset=UTF-8" />'+
    '<script src="/javascripts/headScripts.js"></script>'+ 
    '<link rel="stylesheet" href="/stylesheets/style.css" />'+
    '</head>'+
    '<body>'+
    '<p><a href="/">首页</a></p>'+
    '<p><input id="isAll" type="checkbox" onclick="chooseAll()"/>全选</p>'+
    '<p><button onclick="' + actionName +'()">' + actionName + '</button></p>'+
    '<table width="1000" border="0" cellspacing="0" cellpadding="10" ">' 

    var files = fs.readdirSync('games/')
    for(var i in files)
    { 
      if (files[i]=='.DS_Store') continue
      html = html + '<tr>'
      var gameIdx = files[i].split(segX)[0]
      var gameName = files[i].split(segX)[1]
      var h = '<input id=' + gameIdx + ' type="checkbox" value =' + files[i] + ' />'+gameName
       
      html = html +  '<td>' + h + '</td>'
      html = html + '</tr>'
    }
    
    html = html + '</table></body></html>' 

    return html
}




